// src/stores/RoleStores.js
import { defineStore } from 'pinia'
import { RoleApi } from "@/api/role/index.js";

export const useRoleStore = defineStore('role', {
    state: () => ({
        roleList: [],
        pageInfo: {
            page: 1,
            size: 10,
            total: 0,
            totalPage: 0
        }
    }),
    actions: {
        async list(params = {}) {
            try {
                const response = await RoleApi.pagelist({
                    page: params.page || this.pageInfo.page,
                    size: params.size || this.pageInfo.size,
                    name: params.name || '',
                    code: params.code || '',
                    dataScope: params.dataScope || null,
                    isDelete: params.isDelete || null,
                });

                if (response) {
                    this.roleList = Array.isArray(response?.data.records) ? response.data.records : [];
                    this.pageInfo = {
                        page: response.data.pageNumber || 1,
                        size: response.data.pageSize || 10,
                        total: response.data.totalRow || 0,
                        totalPage: response.data.totalPage || 0
                    };
                }

                return response;
            } catch (error) {
                console.error('获取角色列表失败:', error);
                throw error;
            }
        },

        async createRole(roleData) {
            try {
                // 创建角色时传递所有必要字段，包括aclIds
                const data = {
                    name: roleData.name,
                    code: roleData.code,
                    dataScope: roleData.dataScope,
                    aclIds: roleData.aclIds || [], // 确保传递aclIds
                    isDelete: roleData.isDelete
                };
                const response = await RoleApi.create(data);
                return response;
            } catch (error) {
                console.error('创建角色失败:', error);
                throw error;
            }
        },

        async updateRole(roleData) {
            try {
                // 更新角色时传递所有必要字段，包括aclIds
                const data = {
                    id: roleData.id,
                    name: roleData.name,
                    code: roleData.code,
                    dataScope: roleData.dataScope,
                    aclIds: roleData.aclIds || [], // 确保传递aclIds
                    isDelete: roleData.isDelete
                };
                const response = await RoleApi.updateRole(data);
                return response;
            } catch (error) {
                console.error('更新角色失败:', error);
                throw error;
            }
        },

        async deleteRole(id) {
            try {
                const response = await RoleApi.delete(id);
                return response;
            } catch (error) {
                console.error('删除角色失败:', error);
                throw error;
            }
        }
    }
})
